3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.

  • For example, given array S = {-1 2 1 -4}, and target = 1.
  • The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题目大意:给定数组和一个目标值,数组中有三个数之和与目标值最为接近,返回这三个数的和,值唯一

题目难度:Medium

import java.util.Arrays;

/**
 * Created by gzdaijie on 16/5/15
 * 复杂度O(N*lgN + N*N) = O(N)
 */
public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);

        int len = nums.length;
        int diff = Integer.MAX_VALUE;
        int sum, result = 0;
        int left, right;

        for (int i = 0; i < len - 2; i++) {
            // 避免第一个数重复
            if (i != 0) {
                while (nums[i - 1] == nums[i] && i < len - 2) ++i;
            }

            left = i + 1;
            right = len - 1;
            while (left < right) {
                sum = nums[i] + nums[left] + nums[right];
                if (Math.abs(sum - target) < diff) {
                    diff = Math.abs(sum - target);
                    result = sum;
                }
                if (sum - target > 0) {
                    --right;
                } else if (sum - target < 0) {
                    ++left;
                } else {
                    return target;
                }
            }
        }
        return result;
    }
}
gzdaijie            updated 2016-05-15 01:01:53

results matching ""

    No results matching ""